using Gtk;
using Gdk;
using System;
using System.IO;


namespace iPuz.Game
{	
	public class PicBloc : Gtk.EventBox {
	
#region "Fiealds & Properties"
		private uint[] _correctPosition = null;
		private uint[] _currentPosition = null;
		private bool _isLocked = false;
		
		/// <summary>
		/// Get the correct position of PicBloc
		/// </summary>
		public uint[] CorrectPosition {
			get { return this._correctPosition; }
		}
		
		/// <summary>
		/// Get the current of the PicBloc
		/// </summary>
		public uint[] CurrentPosition {
			get { return this._currentPosition; }
		}
		
		/// <summary>
		/// Get if the PicBloc is locked in correct position
		/// </summary>		
		public bool IsLocked {
			get { return this._isLocked; }
		}
#endregion

		/// <summary>
		/// Create a new PicBloc
		/// </summary>
		/// <param name="strm">
		/// Memory stream that containe png image <see cref="System.IO.MemoryStream"/>
		/// </param>
		/// <param name="imgW">
		/// Pixbuf Width <see cref="System.Int32"/>
		/// </param>
		/// <param name="imgH">
		/// Pixbuf Height <see cref="System.Int32"/>
		/// </param>
		/// <param name="correctPosition">
		/// Correct position <see cref="System.UInt32[]"/>
		/// </param>
		/// <param name="currentPosition">
		/// Current position occupied <see cref="System.UInt32[]"/>
		/// </param>
		public PicBloc(System.IO.MemoryStream strm, int imgW, int imgH, uint[] correctPosition, uint[] currentPosition) : base()
		{
			this.Add (new Gtk.Image (new Gdk.Pixbuf (strm).ScaleSimple(imgW, imgH, Gdk.InterpType.Bilinear)));
			this._correctPosition = correctPosition;
			this._currentPosition = currentPosition;
		}
		
#region "PicBloc Events"
		public delegate void PicBlocUpdateEventHandler(object sender);
		public event PicBlocUpdateEventHandler PicBlocUpdate;

		public void OnPicBlocUpdate()
		{
			if (PicBlocUpdate != null)
				PicBlocUpdate (this);
		}
		
		public void Update (Gdk.Pixbuf pix, uint[] newPos)
		{
			this._correctPosition = newPos;
			((Gtk.Image)this.Child).Pixbuf = pix;

			CheckPosition();
			
			if (_isLocked) {		
				Frame frm = (Frame)this.Parent;
				frm.ModifyBg (StateType.Normal, new Gdk.Color (0, 255, 0));
			}
			
			this.OnPicBlocUpdate();
		}
		
		public bool CheckPosition ()
		{
			if (_correctPosition[0] == _currentPosition[0] && _correctPosition[1] == _currentPosition[1] && 
			    _correctPosition[2] == _currentPosition[2] && _correctPosition[3] == _currentPosition[3]) {
				_isLocked = true;
				return true;
			}
			else
				return false;
		}
#endregion "PicBloc Events"

	
	}
}
